/*
@Copyright:LintCode
@Author:   tjyemail
@Problem:  http://www.lintcode.com/problem/insert-node-in-a-binary-search-tree
@Language: C++
@Datetime: 16-02-09 04:49
*/

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: The root of the binary search tree.
     * @param node: insert this node into the binary search tree
     * @return: The root of the new binary search tree.
     */
    TreeNode* insertNode(TreeNode* root, TreeNode* node) {
        // write your code here
        for(TreeNode *p=root;p;){
            if (p->val>node->val){
                if (p->left==NULL){
                    p->left= new TreeNode(node->val);
                    return root;
                }
                p=p->left;
            }
            else if (p->val <node->val){
                if (p->right==NULL){
                    p->right = new TreeNode(node->val);
                    return root;
                }
                p=p->right;
            }
            else
                return root;
        }
        root = new TreeNode(node->val);
        return root;
    }
};